package net.osc.addrpsr;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

/**
 * User: ken
 * Date: 13-7-29
 */
public class Regions {

    private static Document doc;

    private static String[] provinces;

    private static String[] cities;

    private static String[] districts;


/*
    public static String xmlFromDB() throws SQLException {
        Document doc = Jsoup.parse("<region></region>", "", Parser.xmlParser());
        Elements region = doc.select("region");

        ResultSet provinces = DB.executeQuery("select * from region_code2 where code like '%0000'");
        while (provinces.next()) {
            String code = provinces.getString("code");
            String fullname = provinces.getString("name");
            String name = null;
            if (fullname.contains("省")) {
                name = fullname.replaceAll("省", "");
            } else if (fullname.contains("自治")) {
                name = fullname.replaceAll("(壮族|回族|维吾尔)?自治区", "");
            } else if (fullname.contains("市")) {
                name = fullname.replaceAll("市", "");
            }


            Element province = region.append("<province></province>").select("province").last();
            province.attr("code", code).attr("name", name).attr("fullname", fullname);

            ResultSet cities = DB.executeQuery(String.format("select * from region_code2 where code like '%s%%00' and code <> '%s'", code.substring(0, 2), code));
            while (cities.next()) {
                String code2 = cities.getString("code");
                String fullname2 = cities.getString("name");
                if (fullname2.contains("直辖")) {
                    continue;
                }

                String racesPattern = "汉族|回族|藏族|维吾尔族|苗族|蒙古族|壮族|布依族|朝鲜族|满族|侗族|瑶族|白族|土家族|哈尼族|哈萨克族|傣族|黎族|傈僳族|佤族|畲族|高山族|拉祜族|水族|东乡族|纳西族|景颇族|柯尔克孜族|土族|达斡尔族|仫佬族|羌族|撒拉族|毛南族|仡佬族|锡伯族|阿昌族|普米族|布朗族|塔吉克族|怒族|乌孜别克族|俄罗斯族|鄂温克族|德昂族|保安族|裕固族|京族|塔塔尔族|独龙族|鄂伦春族|赫哲族|门巴族|珞巴族|基诺族|彝族";
                String name2 = fullname2.replaceAll(String.format("(%s)*(自治州|地区|市)$", racesPattern), "");

                Element city = province.append("<city></city>").select("city").last();
                city.attr("code", code2).attr("name", name2).attr("fullname", fullname2);


                ResultSet districts = DB.executeQuery(String.format("select * from region_code2 where code like '%s%%' and code <> '%s'", code2.substring(0, 4), code2));
                while (districts.next()) {
                    String code3 = districts.getString("code");
                    String fullname3 = districts.getString("name");

                    if (fullname3.matches("^(城区)|(市辖区)|(县)$")) {
                        continue;
                    }

                    String name3 = fullname3.replaceAll(String.format("(.{2,}?)(%s)*(自治)*(县|区|市)$", racesPattern), "$1");


                    Element district = city.append("<district></district>").select("district").last();
                    district.attr("code", code3).attr("name", name3).attr("fullname", fullname3);

                }
            }
        }

        return doc.toString();
    }
*/

    public static Document xml() {
        if (doc != null) {
            return doc;
        }

        InputStream is = ClassLoader.getSystemResourceAsStream("region.xml");
        Document doc;
        try {
            doc = Jsoup.parse(is, "UTF-8", "", Parser.xmlParser());
            Regions.doc = doc;
        } catch (IOException e) {
            doc = null;
        }

        return doc;
    }

    public static String[] provinces() {
        if (provinces != null) {
            return provinces;
        }

        List<String> list = new ArrayList<String>();

        Elements elements = xml().select("province:not([fullname~=市$])");
        for (Element element : elements) {
            list.add(element.attr("name"));
        }

        String[] provinces = list.toArray(new String[list.size()]);
        Regions.provinces = provinces;
        return provinces;
    }

    public static String[] cities() {
        if (cities != null) {
            return cities;
        }
        Set<String> list = new HashSet<String>();

        Elements elements = xml().select("[fullname~=.*市$]");
        for (Element element : elements) {
            list.add(element.attr("name"));
        }
        elements = xml().select("city");
        for (Element element : elements) {
            String fullname = element.attr("fullname");
            if (!fullname.endsWith("区") || !fullname.endsWith("县")) {
                list.add(element.attr("name"));
            }
        }

        String[] cities = list.toArray(new String[list.size()]);
        Regions.cities = cities;
        return cities;
    }

    public static String[] districts() {
        if (districts != null) {
            return districts;
        }

        Set<String> set = new HashSet<String>();

        Elements elements = xml().select("[fullname~=.*(县|区)$]");
        for (Element element : elements) {
            set.add(element.attr("name"));
        }
        elements = xml().select("district");
        for (Element element : elements) {
            String fullname = element.attr("fullname");
            if (!fullname.endsWith("市")) {
                set.add(element.attr("name"));
            }
        }

        String[] districts = set.toArray(new String[set.size()]);
        Regions.districts = districts;
        return districts;
    }

    public static String[] districtsOf(String city) {
        Elements elements = xml().select("city[name=" + city + "] district");
        Set<String> set = new HashSet<String>();
        for (Element e : elements) {
            String name = e.attr("name");
            if (name.length() > 1) {
                set.add(name);
            }
        }
        return set.toArray(new String[set.size()]);
    }

    public static void main(String[] args) {
        String[] ss = cities();
        for (String s : ss) {
            System.out.println("s = " + s);
        }
    }

    public static void reset() {
        provinces = null;
        cities = null;
        districts = null;
    }

}
